<template>
  <div class="box">
    <header class="header detail">
      <transition name="fade">
        <van-nav-bar @click-left='$router.back()' v-if='top<50' @click-right.stop='rightNav'>
          <template #left>
            <van-icon name="arrow-left" size='20'/>
          </template>
          <template #title>
          </template>
          <template #right>
            <van-icon name="weapp-nav" size='20'/>
            <ul class="rightNavList" v-show='show'>
              <li>首页</li>
              <li>分类搜索</li>
              <li>购物车</li>
              <li>我的</li>
              <li>
                <van-cell title="分享" @click.stop="showShare = true" />
                <van-share-sheet
                  v-model="showShare"
                  title="立即分享给好友"
                  :options="options"
                  @select="onSelect"
                  cancel-text=''
                />
              </li>
            </ul>
          </template>
        </van-nav-bar>
      </transition>
      <transition name="fade">
        <van-nav-bar @click-left='$router.back()' v-if='top>=50' class='scrollNav' @click-right.stop='rightNav'>
          <template #left>
            <van-icon name="arrow-left" size='20' />
          </template>
          <template #title>
            <van-tabs v-model="active">
              <van-tab title="商品"></van-tab>
              <van-tab title="评价"></van-tab>
              <van-tab title="详情"></van-tab>
              <van-tab title="推荐"></van-tab>
            </van-tabs>
          </template>
          <template #right>
            <van-icon name="weapp-nav" size='20' />
            <ul class="rightNavList" v-show='show'>
              <li>首页</li>
              <li>分类搜索</li>
              <li>购物车</li>
              <li>我的</li>
              <li>
                <van-cell title="分享" @click.stop="showShare = true" />
                <van-share-sheet
                  v-model="showShare"
                  title="立即分享给好友"
                  :options="options"
                  @select="onSelect"
                  cancel-text=''
                />
              </li>
            </ul>
          </template>
        </van-nav-bar>
      </transition>
    </header>
    <!-- 二级路由,命名路由用name，未命名路由默认路由为default -->
    <!-- 一个容器有一个组件渲染，那么先去创建2个组件，再components文件夹下 -->
    <!-- 命名视图也叫多视图渲染 -->
    <!-- <router-view name="img"></router-view>
    <router-view name="msg"></router-view> -->
    <!-- <p>接收到的id为：{{$route.params.id}}</p> -->
    <!-- <p>接收到的id为：{{$route.params.id}}</p> -->
    <div class="proCount" ref='content'>
      <van-swipe class="my-swipe" indicator-color="white" @change='onChange' ref='swipe'>
        <van-swipe-item v-for='(item,idx) in proImg' :key='idx' @click='proview(idx)' >
          <van-image width="100%" height="4rem" fit='cover' :src="item" />
        </van-swipe-item>
        <template #indicator>
            <div class="custom-indicator">
              {{ current + 1 }}/{{length}}
            </div>
        </template>
      </van-swipe>
      <div class="proInfo">
       <h3>商品名称：{{proName}}</h3>
        <p>分类：{{column}}</p>
        <p>品牌：{{brand}}</p>
        <p>价格：{{price}}</p>
        <p>描述：{{describe}}</p>
        <p>库存：{{stock}}</p>
        <p>销量：{{sales}}</p>
        <p>折扣：{{discount}}</p>
        <p>评分：{{score}}</p>
      </div>
      <div class="proInfo">
       <h3>商品名称：{{proName}}</h3>
        <p>分类：{{column}}</p>
        <p>品牌：{{brand}}</p>
        <p>价格：{{price}}</p>
        <p>描述：{{describe}}</p>
        <p>库存：{{stock}}</p>
        <p>销量：{{sales}}</p>
        <p>折扣：{{discount}}</p>
        <p>评分：{{score}}</p>
      </div>
      <div class="proInfo">
       <h3>商品名称：{{proName}}</h3>
        <p>分类：{{column}}</p>
        <p>品牌：{{brand}}</p>
        <p>价格：{{price}}</p>
        <p>描述：{{describe}}</p>
        <p>库存：{{stock}}</p>
        <p>销量：{{sales}}</p>
        <p>折扣：{{discount}}</p>
        <p>评分：{{score}}</p>
      </div>
    </div>

   <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" color="#07c160" />
      <van-goods-action-icon icon="cart-o" text="购物车" @click='$router.push("/cart")' :badge="sum"/>
      <van-goods-action-icon :icon="isStar ? 'star' : 'star-o'" :text="isStar ? '已收藏' : '收藏'" color="#ff5000" @click='Star' />
      <van-goods-action-button type="warning" text="加入购物车" @click='addCart' />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import Vue from 'vue'
import { Swipe, SwipeItem, Image as VanImage, ImagePreview, Toast, GoodsAction, GoodsActionIcon, GoodsActionButton, NavBar, Icon, Tab, Tabs, ShareSheet, Cell } from 'vant'
import { getDetail, addCart, getCart } from '../../api/index.js'

Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(VanImage)
Vue.use(ImagePreview)
Vue.use(Toast)
Vue.use(GoodsAction)
Vue.use(GoodsActionIcon)
Vue.use(GoodsActionButton)
Vue.use(NavBar)
Vue.use(Icon)
Vue.use(Tab)
Vue.use(Tabs)
Vue.use(ShareSheet)
Vue.use(Cell)
export default {
  data () {
    return {
      proName: '',
      column: '',
      brand: '',
      logo: '',
      proImg: '',
      price: 910,
      describe: '',
      stock: 11,
      sales: 1900,
      discount: 8,
      score: 4.8,
      current: 0,
      length: 0,
      swipe: '',
      cartList: [],
      active: 0,
      top: 0,
      show: false,
      showShare: false,
      options: [
        { name: '微信', icon: 'wechat' },
        { name: '微博', icon: 'weibo' },
        { name: '复制链接', icon: 'link' },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' }
      ],
      isStar: false,
      sum: 0
    }
  },
  props: ['id'],
  mounted () {
    // 这是在js中拿id
    // console.log(this.$route.params.id)
    getDetail({
      // this.$route.params.id
      id: this.id
    }).then(res => {
      this.proImg = [res.data.data.proImg, 'https://img.yzcdn.cn/vant/apple-1.jpg', 'https://img.yzcdn.cn/vant/apple-2.jpg']
      this.length = this.proImg.length
      this.proName = res.data.data.proName
      this.column = res.data.data.column
      this.brand = res.data.data.brand
      this.price = res.data.data.price
      this.describe = res.data.data.describe
      this.stock = res.data.data.stock
      this.sales = res.data.data.sales
      this.discount = res.data.data.discount
      this.score = res.data.data.score
    })
    // 详情页中购物车右上角的个数
    getCart({
      userId: localStorage.getItem('userId')
    }).then(res => {
      if (res.data.state === 200) {
        console.log(res.data.data.proData)
        this.cartList = res.data.data.proData
      } else {
        console.log('没有数据，空的购物车')
      }
    })
    this.$refs.content.addEventListener('scroll', () => {
      // 注意箭头函数
      this.top = this.$refs.content.scrollTop
      // console.log(this.top)
      // 滑动是设置当前项
      if (this.top < 400) {
        this.active = 0
      } else if (this.top >= 400 && this.top < 800) {
        this.active = 1
      } else if (this.top >= 800 && this.top < 1200) {
        this.active = 2
      } else if (this.top >= 1200) {
        this.active = 3
      }
    })
    document.addEventListener('click', () => {
      this.show = false
    })
    // 初始时,先读取数据,是否有没有被收藏过
    let isStarData = localStorage.getItem('star')
    isStarData = isStarData ? JSON.parse(isStarData) : []
    const onoff = isStarData.some((val, idx) => {
      return val === this.id
    })
    if (onoff) {
      this.isStar = true
    }
  },
  computed: {
    // proSum () {
    //   return this.cartList.reduce((prev, next) => {
    //     return prev + (next.num - 0)
    //   }, 0)
    // }
  },
  methods: {
    onChange (index) {
      this.current = index
    },
    proview (idx) {
      // console.log(item)
      const that = this
      ImagePreview({
        images: this.proImg,
        startPosition: idx,
        onClose (url) {
          // {index: 1, url: "https://img.yzcdn.cn/vant/apple-1.jpg"}
          // console.log(url)
          // console.log(that.$refs.swipe)
          that.$refs.swipe.swipeTo(url.index)
          Toast('关闭')
        }
      })
    },
    addCart () {
      // 前端验证,md5加密
      if (localStorage.getItem('isLogin') === 'ok') {
        addCart({
          // 在本地存储找
          userId: localStorage.getItem('userId'),
          // this.$route当前路由
          proId: this.id
          // 在拦截器中发了
          // token: localStorage.getItem('token')
        }).then((res) => {
          getCart({
            userId: localStorage.getItem('userId')
          }).then(res => {
            if (res.data.state === 200) {
              this.cartList = res.data.data.proData
            } else {
              console.log('没有数据，空的购物车')
            }
          })
        })
      } else {
        this.$router.push('/login')
      }
    },
    rightNav () {
      this.show = !this.show
    },
    onSelect (option) {
      Toast(option.name)
      this.showShare = false
    },
    onCancel () {},
    Star () {
      this.isStar = !this.isStar
      let isStarData = localStorage.getItem('star')
      isStarData = isStarData ? JSON.parse(isStarData) : []
      // console.log(isStarData)
      let i = 0
      const onoff = isStarData.some((val, idx) => {
        i = idx
        return val === this.id
      })
      // 如果有就删,没有就存
      if (onoff) {
        isStarData.splice(i, 1)
      } else {
        isStarData.push(this.id)
      }
      localStorage.setItem('star', JSON.stringify(isStarData))
    }
  }
}
</script>

<style lang="scss">
.header.detail {
  .my-swipe .van-swipe-item {
    height: 4rem;
   }
  position: fixed;
  top:0;
  left: 0;
  z-index: 10;
  width: 100%;
  height: 0.46rem;
  text-align: center;
  font: 0.24rem/0.46rem "";
  .van-nav-bar {
    position: fixed;
    top:0;
    left: 0;
    width: 100%;
    background-color: rgba(0,0,0,0);
    border-bottom: none;
    .van-nav-bar__left{
      background: #333;
      border-radius: 50%;
      padding: 0px;
      width:0.3rem;
      height: 0.3rem;
      margin: 0.1rem 0 0 0.1rem;
      justify-content: center;
    }
    .van-nav-bar__right {
      background: #333;
      border-radius: 50%;
      padding: 0px;
      width:0.3rem;
      height: 0.3rem;
      margin: 0.1rem 0.1rem 0 0 ;
      justify-content: center;
    }
    .van-icon {
      color: #fff;
    }
    &::after{
      border: none;
    }
  }
  .scrollNav.van-nav-bar {
    background: #fff;
    .van-nav-bar__left {
      background: none;
    }
    .van-nav-bar__right {
      background: none;
    }
    .van-icon {
      color: #666;
    }
    .van-nav-bar__title {
      display: flex;
      .van-tab {
        padding: 0 0.1rem;
      }
    }
  }
  .rightNavList {
    position: absolute;
    top: 0.38rem;
    right: 0;
    width: 0.7rem;
    background: rgba(0,0,0,.9);
    color: #fff;
    list-style: none;
    padding: 0 0.1rem;
    margin: 0;
    border-radius: 0.1rem;
    li{
      border-bottom: 1px solid hsla(0, 0%, 100%, .2);
      padding: 0.05rem 0;
      text-align: left;
    }
    .van-cell {
      padding: 0.05rem 0;
      text-align: left;
      background: none;
      color: #fff;
      position: static;
    }
  }
}

.box{
  display: flex;
  .proCount{
    flex: 1;
    overflow: auto;
    .proInfo{
      // 安全距离,设置0.5rem，可以把最后一个评分挤出来，要是不设置就少一个评分
      padding: 0px 0.1rem 0.5rem;
    }
  }
  .custom-indicator {
    position: absolute;
    right: 5px;
    bottom: 5px;
    padding: 2px 5px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
  }
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 2s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>
